<template>
    <view class="pay_con">
        <view class="icon">
            <image v-if="payStatus == 'payed'" src="https://jdkj-1306681707.cos.ap-nanjing.myqcloud.com/S0000260/image/proImg_202509221121239508.png"  mode="aspectFit" />
            <image v-if="payStatus == 'unpay'" src="https://jdkj-1306681707.cos.ap-nanjing.myqcloud.com/S0000260/image/proImg_202509191712136148.png"  mode="aspectFit" />
        </view>
        <view class="title">{{ {unpay: '等待支付...', payed: '支付成功'}[payStatus]}}</view>
        <view class="price"><text>￥</text>{{payPrice}}</view>

        <view class="pay_info">
            <view>门店号： <text>{{orderDetail.storeNo}}</text> </view>
            <view>订单编号： <text>{{orderDetail.orderNo}}</text></view>
        </view>
        <view class="btns" v-if="orderDetail.orderNo">
            <view v-if="payStatus == 'unpay'" @click="autoPay" class="btn continue">继续支付</view>
            <template v-if="payStatus == 'payed'">
                <!-- #ifdef MP-WEIXIN -->
                <button class="btn backhome" open-type="launchApp" app-parameter="wechat" @error="launchAppError">返回APP</button>
                <!-- #endif -->

                <!-- #ifdef MP-ALIPAY -->
                <!-- <view v-if="payStatus == 'payed'" @click="backHome" class="btn backhome">返回APP</view> -->
                <!-- #endif -->
            </template>
        </view>

    </view>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { orderInfo, getPayType, collect, userDepositPay,orderRentSign, createOrderContract,
    queryOrderContract, jumpRentCycleSign, qrCollectCancel, getUserContractInfo, changeUserContractInfo } from '@/api/order'
import { confirmBindCard, lockUserCyclePayApply, checkRentUserStatus } from '@/api/user'
import {ref, reactive } from "vue"
import { userLogin, getUserInfo } from "@/api/user";
import { useStore } from 'vuex';
import Interact from "@/utils/interact";
const Store = useStore();
let platform = ''
// #ifdef MP-WEIXIN
platform = '00'
// #endif

// #ifdef MP-ALIPAY
platform = '03'
// #endif

const orderNo = ref('')
const orderDetail = ref<any>({})
const payPrice = ref('')
let moreData = {}
let payTypeId = ''
let token = ''
onLoad(async (options: any) => {
    console.log(options, 'dddd');

    orderNo.value = options.orderNo
    payPrice.value = options.price
    payTypeId = options.payTypeId
    token = options.token
    moreData = options.params ? JSON.parse(options.params) : {}
    await login()
    getOrderInfo()
})

let localToken = ''
const login = () => {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            scopes: 'auth_user',
            success: loginRes => {
                userLogin({
                    loginData: JSON.stringify({
                        code: loginRes.code,
                        iv: '',
                        token: token
                    }),
                    platform,
                    storeNo: Store.state.shop.storeNo,
                }).then(res => {
                    localToken = res.data.login.token
                    resolve()
                })
            }
        })
    })

}


const getOrderInfo = () => {
    return orderInfo({
        orderNo: orderNo.value,
        token: localToken,
        platform,
    }).then(res => {
        orderDetail.value = res.data
        if(payTypeId) {
            autoPay()
        } else {
            getPayTypeId()
        }
    })
}


const getPayTypeId = () => {
    let data:any = {
        token: localToken,
        storeNo: orderDetail.value.storeNo,
        platform,
    }
    // #ifdef MP-WEIXIN
    data.paytype = 'WXMINI'
    // #endif

    // #ifdef MP-ALIPAY
    data.paytype = 'ALIMINI'
    // #endif
    getPayType(data).then(res => {
        payTypeId = res.data[0]?.payTypeId || ''
        if(payTypeId) {
            autoPay()
        } else {
            Interact.modal('暂无支付方式')
        }
    }, err => {
        Interact.modal('支付方式获取失败，请稍后再试')
    })
}


const autoPay = async () => {
    if (!payTypeId) {
        return Interact.toast('请选择支付方式')
    }
    uni.showLoading({
        title: '加载中',
        mask: true,
    })

    collect({
        collectMoney: payPrice.value,
        orderNo: orderDetail.value.orderNo,
        payTypeId: payTypeId,
        token: localToken,
        platform,
        ...moreData,
    }).then(res => {
        // #ifdef MP-ALIPAY
        my.tradePay({
            tradeNO: res.data.payData.ali_trade_no,
            success: async (res: any) => {
                uni.hideLoading()
                console.log('success', res);
                if(res.resultCode == '6001') {
                    return await payCancel()
                }
                paySuccess()
            },
            fail: (err: any) => {
                console.log(err);
                payCancel()
                uni.hideLoading()
                Interact.toast('支付失败')
            },
            complete: (res: any) => {
                console.log(res, 'compleeeeeeee');
            }
        })
        // #endif


        // #ifdef MP-WEIXIN
        (uni as any).requestPayment({
            provider: 'wxpay',
            timeStamp: res.data.payData.timeStamp + '',
            nonceStr: res.data.payData.nonceStr,
            package: res.data.payData.package,
            signType: res.data.payData.signType,
            paySign: res.data.payData.paySign,
            success(res) {
                uni.hideLoading()
                paySuccess()
            },
            fail() {
                uni.hideLoading()
                Interact.toast('支付失败')
                payCancel()
            }
        });
        // #endif
    }, (err: any) => {
        uni.hideLoading()
        payCancel()
        Interact.toast(err.msg)
    })
}

// const payStatus = ref('payed') // unpay - 未支付  payed - 已支付
const payStatus = ref('unpay') // unpay - 未支付  payed - 已支付
const paySuccess = () => {
    payStatus.value = 'payed'
}

const payCancel = () => {
    return qrCollectCancel({
        orderNo: orderNo.value,
        token: localToken,
    })
}


const launchAppError = (e: any) => {
    Interact.toast(e.detail.errMsg)
}


const backHome = () => {
    Interact.toast('test')
    my.ap.openURL({
        url: 'https://sjx.sojiandan.com/pay/ali_suc.html?url=' + encodeURIComponent('weixin://'),
        success: (res) => {
            console.log('openURL success', res)
        },
        fail: (err) => {
            console.log('openURL success', err)
        }

    })
    //     my.exitMiniProgram()

    // #ifdef MP-ALIPAY
    // if(plus.os.name == 'Android') {
    // }
    // #endif
}



</script>
<style lang="scss" scoped>
.pay_con {
    height: 100vh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 60rpx;
    .icon{
        image{
            width: 60rpx;
            height: 60rpx;
        }
    }
    .title{
        margin-top: 50rpx;
        font-weight: bold;
        font-size: 36rpx;
    }
    .price{
        font-size: 80rpx;
        font-weight: bold;
        margin-top: 150rpx;
        text{
            font-size: 46rpx;
            margin-right: 5rpx;
        }
    }
    .pay_info{
        margin-top: 100rpx;
        border-top: 1px solid #e2e2e2;
        width: 660rpx;
        padding: 30rpx;
        view{
            line-height: 50rpx;
            display: flex;
            justify-content: space-between;
            color: #888;
            font-size: 26rpx;
        }
    }
    .btns{
        margin-top: 100rpx;
        .btn{
            width: 650rpx;
            height: 70rpx;
            border-radius: 35rpx;
            background: #1890ff;
            color: #fff;
            font-size: 24rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            &.continue{
                background-color: #ee3908;
            }
            &.backhome{
                background-color: #147bc0;
            }

        }
    }

}

</style>